package util

import (
	"bytes"
	"crypto/md5"
	"crypto/sha1"
	"fmt"
	"math/rand"
	"strconv"
	"strings"
	"time"

	"github.com/fatih/structs"
	"github.com/satori/go.uuid"
)

// MD5Hash MD5哈希值
func MD5Hash(b []byte) string {
	h := md5.New()
	h.Write(b)
	return fmt.Sprintf("%x", h.Sum(nil))
}

// MD5HashString MD5哈希值
func MD5HashString(s string) string {
	return MD5Hash([]byte(s))
}

// SHA1Hash SHA1哈希值
func SHA1Hash(b []byte) string {
	h := sha1.New()
	h.Write(b)
	return fmt.Sprintf("%x", h.Sum(nil))
}

// SHA1HashString SHA1哈希值
func SHA1HashString(s string) string {
	return SHA1Hash([]byte(s))
}

// UUID 获取UUID
func UUID() string {
	return uuid.Must(uuid.NewV4()).String()
}

// GenerateRecordID
func GenerateRecordID() string {
	var t int64
	t = time.Now().UnixNano()*100 + rand.Int63n(100)
	return strconv.FormatInt(t, 10)
}

// StructToMap 转换struct为map
func StructToMap(s interface{}) map[string]interface{} {
	return structs.Map(s)
}

// Trim 去除空格
func Trim(s string) string {
	return strings.TrimSpace(s)
}

// ParseLevelCodes 解析分级码
func ParseLevelCodes(levelCode string) []string {
	if len(levelCode) < 2 {
		return nil
	}
	var (
		codes []string
		root  bytes.Buffer
	)

	for i := range levelCode {
		idx := i + 1
		if idx%2 == 0 {
			root.WriteString(levelCode[idx-2 : idx])
			codes = append(codes, root.String())
		}
	}

	codes = append(codes, levelCode)

	return codes
}
